package com.okaysoft.ofb

import org.springframework.dao.DataIntegrityViolationException
import grails.converters.JSON
import org.apache.commons.lang.time.DateUtils

class TaskController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index() {
        redirect(action: "list", params: params)
    }

    def list() {

    }

    def listJson() {
        params.max = Math.min(params.rows ? params.int('rows') : 10, 100)
        params.page = params.page ? params.int('page') : 0
        params.offset = (params.page - 1) * params.max
        def tasks// = Task.list(params)
        params.status = Task.Status.NOTCOMPLETE
       // tasks = Task.executeQuery("select distinct a.device from Task a where a.status=:status order by a.id desc",[status:Task.Status.NOTCOMPLETE],params)
        tasks = Task.findAllByStatus(Task.Status.NOTCOMPLETE,params)
        tasks = tasks.collect {task->
            def d = task.device
            //[id:task.id,name:task?.device?.name+"/"+task?.device?.code,addr:task?.device?.location?.addr,
            //        userName:task?.user?.name,assignDate:task.assignDate.format('yyyy-MM-dd'),'device.id':task.device?.id,'user.id':task.user?.id]
            ['device.id':d?.id,name:d?.name,addr:d?.location?.addr]
        }
        tasks.unique()
        render([rows:tasks,total:Task.count()] as JSON)
    }

    def save() {
        def taskInstance
        params.description = params.task_description
        if (params.id) {
            taskInstance = Task.get(params.id)
        }

        if (!taskInstance) {
            taskInstance = new Task()
        }

        if (params.assignDate)  {
            params.assignDate=DateUtils.parseDate(params.assignDate,'yyyy-MM-dd')
        }

        taskInstance.properties = params
        taskInstance.status = Task.Status.NOTCOMPLETE
        taskInstance.type = Task.Type."${params.task_status}"
        if (!taskInstance.save(flush: true)) {
            log.error(taskInstance.errors)
            def failure = [status: 0,msg:message(code: 'default.save.failure.message', default: 'Save failure')] as JSON
            render(failure.toString())
            return
        }

        def succ = [status: 1,msg:message(code: 'default.save.success.message', default: 'Save success')] as JSON
        render(succ.toString())
    }

    def show() {
        def taskInstance = Task.get(params.id)
        if (!taskInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'task.label', default: 'Task'), params.id])
            redirect(action: "list")
            return
        }

        [taskInstance: taskInstance]
    }

    def delete() {
        def taskInstance = Task.get(params.id)
        if (!taskInstance) {
            def notfound = [status: 0, msg:  message(code: 'default.not.found.message', args: [message(code: 'task.label', default: 'Task'), params.id])] as JSON
            render(notfound.toString())
            return
        }

        try {
            taskInstance.delete(flush: true)
            def succ = [status: 1, msg:  message(code: 'default.deleted.message', args: [message(code: 'task.label', default: 'Task'), params.id])] as JSON
            render(succ.toString())
        }
        catch (DataIntegrityViolationException e) {
            def failure = [status: 0, msg:  message(code: 'default.not.deleted.message', args: [message(code: 'task.label', default: 'Task'), params.id])] as JSON
            render(failure.toString())
        }
    }

    def complete() {
        def status = params.status
        def deviceId = params.deviceId
        def sta = Task.Status."$status"
        def tasks = []

        if (deviceId) {
            def device = Device.get(deviceId)
            if (device) {
                tasks += Task.findAllByDeviceAndStatus(device,sta)
            }
        }
        tasks = tasks.collect {task->
            [id: task.id,type:task.type.label,task_status:task.type.name(),assignDate:task?.assignDate?.format('yyyy-MM-dd'),description:task.description,result:task.result,
                    completeDate:"${task?.completeUser?.name}/${task?.completeDate?.format('yyyy-MM-dd')}",opticalcableName:task.opticalcableName,
                    opticalcableCodeStart:task.opticalcableCodeStart,opticalcableCodeEnd:task.opticalcableCodeEnd,direction:task.direction,
                    pair:task.pair,terminal:task.terminal]
        }
        tasks = tasks as JSON
        render(tasks.toString())
    }
}
